/*
 *  startgame_window.cpp
 */

#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
#include "client_app.h"
#include "client_window.h"
#include "startgame_window.h"
#include "../../common/src/debug.h"
#include "../../common/src/lock.h"
#include "../../common/src/message.h"
#include "../../common/src/synchro_vector.h"
#include "../../common/src/util.h"

StartGameWindow::StartGameWindow(BaseObjectType* object,
                                 const Glib::RefPtr<Gtk::Builder>& builder)
                                :ClientWindow(object, builder) {
    builder->get_widget("MinPlayersLabel", lbMinPlayers);
    builder->get_widget("JoinedPlayersLabel", lbJoinedPlayers);
	builder->get_widget("StartGameButton", btnStartGame);
	builder->get_widget("CancelGameButton", btnCancelGame);
	btnStartGame->signal_clicked().connect(sigc::mem_fun(*this,
                                                &StartGameWindow::onStartGame));
	btnCancelGame->signal_clicked().connect(sigc::mem_fun(*this,
                                               &StartGameWindow::onCancelGame));
    players_ready = 1;
    setGameJoinedPlayers("1");    //owner auto-join the game
}

StartGameWindow::~StartGameWindow() {}

void StartGameWindow::setLobbyWindow(Gtk::Window* window) {
    winLobby = window;
}

void StartGameWindow::setGameMinPlayers(std::string min_players) {
    lbMinPlayers->set_text(min_players);
}

void StartGameWindow::setGameJoinedPlayers(std::string joined_players) {
    lbJoinedPlayers->set_text(joined_players);
}

void StartGameWindow::onStartGame() {
    Lock lock(&mutex);
    app->requestStartGame();
    while (status == STATUS_WAITING) {
        usleep(1);
    }
    if (status == STATUS_OK) {
        PRINT("START_GAME_INVOKED");
        //winLobby->show();
        //get_application()->add_window(*winLobby);
        //get_application()->remove_window(*this);
        //hide();
    }
}

void StartGameWindow::onCancelGame() {
    Lock lock(&mutex);
    app->requestAbortGame();
    status = STATUS_WAITING;
    while (status == STATUS_WAITING) {
        usleep(1);
    }
    if (status == STATUS_OK) {
        winLobby->show();
        get_application()->add_window(*winLobby);
        get_application()->remove_window(*this);
        hide();
    }
}

void StartGameWindow::notifyGameAbortOk(ClientApp* app) {
    status = STATUS_OK;
}

void StartGameWindow::notifyGameStartOk(ClientApp* app) {
    status = STATUS_OK;
}

void StartGameWindow::notifyPlayerJoined(ClientApp* app) {
    setGameJoinedPlayers(Util::itos(++players_ready));
}

void StartGameWindow::notifyPlayerDissevered(ClientApp* app) {
    setGameJoinedPlayers(Util::itos(--players_ready));
}

//{+}

